package com.qf.controller;


import com.qf.entity.User;
import com.qf.service.Impl.UserLoginServiceImpl;
import com.qf.service.UserLoginService;
import com.qf.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/user")
public class UserLoginController extends BaseController {

    public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.收参
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //2.调用业务
        UserLoginService userLoginService = new UserLoginServiceImpl();
        User user = userLoginService.userLogin(username,password);

        //3.根据结果跳转
        if (user != null){
            //3.1将登录成功的用户存储在session里
            request.getSession().setAttribute("user",user);
            return Constants.REDIRECT+"/index.jsp";
        }else {
            request.setAttribute("msg","账户或密码错误");
            return Constants.FORWARD+"/login.jsp";
        }
    }

    public String outLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.getSession().removeAttribute("user");

        return Constants.REDIRECT + "/login.jsp";
    }

    public String checkOldPassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");
        Integer i = 1;
        String oldpassword = request.getParameter("oldpassword");
        if (oldpassword.equals(user.getPassword())) {
            return i.toString();
        } else {
            i = 0;
            return i.toString();
        }
    }

    public String updatePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");
        String repassword = request.getParameter("repassword");
        UserLoginService userLoginService = new UserLoginServiceImpl();
        Integer i = userLoginService.updatePassword(repassword, user.getUsername());
        return i.toString();
    }
}
